package com.example.fyptest3;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.drawable.ColorDrawable;
import android.util.FloatMath;
import android.view.Display;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;

public class FullScreenActivity extends Activity implements OnTouchListener{

	// these matrices will be used to move and zoom image
		private Matrix matrix = new Matrix();
		private Matrix savedMatrix = new Matrix();
		// we can be in one of these 3 states
		private static final int NONE = 0;
		private static final int DRAG = 1;
		private static final int ZOOM = 2;
		private int mode = NONE;
		// remember some things for zooming
		private PointF start = new PointF();
		private PointF mid = new PointF();
		private float oldDist = 1f;
		private float d = 0f;
		private float newRot = 0f;
		private float[] lastEvent = null;
		
		//default size
		private boolean defaultSize = true;
		
		ImageView image;
		String image_path;
		
		private GestureDetector gestureDetector;
		View.OnTouchListener gestureListener;
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_full_screen);
		//change title bar color to CYAN
		ActionBar bar = getActionBar();
		bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00C4CD")));
		getWindow().setFormat(PixelFormat.RGBA_8888);
		Intent i = getIntent();
		String image_n = i.getStringExtra("image_name");
		image_path = i.getStringExtra("image_path");
		setTitle(image_n);
		//set image to ui
		image = (ImageView)findViewById(R.id.imageView_full);
		Bitmap bitmapImage = BitmapFactory.decodeFile(image_path);
		
		int w = bitmapImage.getWidth();
		int h = bitmapImage.getHeight();
		
		Display display = getWindowManager().getDefaultDisplay();
		int dw = display.getWidth();
		int dh = display.getHeight();
				
		image.setImageBitmap(bitmapImage);
		image.setOnTouchListener(this);
		
		Matrix m = image.getImageMatrix();
		if(w<=dw && h<=dh){
			m.postTranslate((float)(dw-w)/2, (float)(dh-h)/2);
			matrix.postTranslate((float)(dw-w)/2, (float)(dh-h)/2);
		}else{
			float[] arr = calcScaleWidthHeight(w, h, dw, dh);
			float ww = ((float)dw-w*arr[0])/2;
			float hh = ((float)dh-h*arr[1])/2;
			m.postScale(arr[0], arr[1]);
			matrix.postScale(arr[0], arr[1]);
			matrix.postTranslate(ww, hh);
			m.postTranslate(ww, hh);
			
//Toast.makeText(FullScreenActivity.this, Float.toString(hh), Toast.LENGTH_LONG).show();
			
		}
		image.setImageMatrix(m);
		image.invalidate();
		
		//catch double tap on imageview
		gestureDetector = new GestureDetector(this, new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        };
        
      //  image.setOnTouchListener(gestureListener);
		
	}
	
	public class MyGestureDetector extends SimpleOnGestureListener {

		@Override
		public boolean onDown(MotionEvent e){
			
			
Toast.makeText(FullScreenActivity.this, "Double Tap occured", Toast.LENGTH_SHORT).show();
			return true;
			
		}
		
	}
	
	public float[] calcScaleWidthHeight(int w, int h, int dw, int dh){
		float[] arr = new float[2];
		float p = (float)w / (float)h; //proportion of image btw width and height
		arr[0] = (float)dw / w;
		float b = (float)dw / p;
		arr[1] = b / h;
		return arr;
	} 

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_full_screen, menu);
		return true;
	}

	
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		ImageView view = (ImageView) v;
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
//Toast.makeText(FullScreenActivity.this, Integer.toString(event.getAction()), Toast.LENGTH_SHORT).show();
				if(!defaultSize){
					savedMatrix.set(matrix);
					start.set(event.getX(), event.getY());
					mode = DRAG;
					lastEvent = null;
				}
			break;
			case MotionEvent.ACTION_POINTER_DOWN:
				defaultSize = false;
				oldDist = spacing(event);
				if (oldDist > 10f) {
					savedMatrix.set(matrix);
					midPoint(mid, event);
					mode = ZOOM;
				}
				lastEvent = new float[4];
				lastEvent[0] = event.getX(0);
				lastEvent[1] = event.getX(1);
				lastEvent[2] = event.getY(0);
				lastEvent[3] = event.getY(1);
				d = rotation(event);
				break;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_POINTER_UP:
				mode = NONE;
				lastEvent = null;
				break;
			case MotionEvent.ACTION_MOVE:
				if (mode == DRAG) {
					matrix.set(savedMatrix);
					float dx = event.getX() - start.x;
					float dy = event.getY() - start.y;
					matrix.postTranslate(dx, dy);
				} else if (mode == ZOOM) {
					float newDist = spacing(event);
					if (newDist > 10f) {
						matrix.set(savedMatrix);
						float scale = (newDist / oldDist);
						matrix.postScale(scale, scale, mid.x, mid.y);
					}

					//limit max/min scale size
					float[] f = new float[9];
					matrix.getValues(f);
				    float scaleX = f[Matrix.MSCALE_X];
				    float scaleY = f[Matrix.MSCALE_Y];
				
				    if(scaleX <= 0.3f)
			            matrix.postScale((0.2f)/scaleX, (0.2f)/scaleY, mid.x, mid.y);
				    else if(scaleX >= 2.5f) 
			            matrix.postScale((2.5f)/scaleX, (2.5f)/scaleY, mid.x, mid.y);
					
				
					if (lastEvent != null && event.getPointerCount() == 3) {
						newRot = rotation(event);
						float r = newRot - d;
						float[] values = new float[9];
						matrix.getValues(values);
						float tx = values[2];
						float ty = values[5];
						float sx = values[0];
						float xc = (view.getWidth() / 2) * sx;
						float yc = (view.getHeight() / 2) * sx;
						matrix.postRotate(r, tx + xc, ty + yc);
					}
				}
				break;
			}
			view.setImageMatrix(matrix);
			
			return true;
	}
	
	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
		}
	
	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
		}
	private float rotation(MotionEvent event) {
		double delta_x = (event.getX(0) - event.getX(1));
		double delta_y = (event.getY(0) - event.getY(1));
		double radians = Math.atan2(delta_y, delta_x);
		return (float) Math.toDegrees(radians);
		}

//Toast.makeText(getApplicationContext(), Float.toString(h*arr[1]), Toast.LENGTH_LONG).show();
//END	
}
